package cn.com.controller.frontController;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import cn.com.Enum.SessionAttr;
import cn.com.Enum.UserAuth;
import cn.com.annotation.Auth;
import cn.com.constant.Code;
import cn.com.db.dto.CartItemDto;
import cn.com.db.model.Cart;
import cn.com.db.model.CartItem;
import cn.com.db.model.Goods;
import cn.com.db.model.Store;
import cn.com.db.service.CartItemService;
import cn.com.db.service.CartService;
import cn.com.db.service.GoodsService;
import cn.com.db.service.StoreService;
import cn.com.util.DataResult;
import cn.com.util.JsonUtil;
import cn.com.util.SessionUtil;
import cn.com.util.TimeUtil;
import cn.com.util.UidUtil;

@Auth(UserAuth.USER)
@RestController
@RequestMapping("/front/cart")
public class CartController {

	Logger logger = Logger.getLogger(CartController.class);
	@Autowired
	GoodsService goodsService;
	@Autowired
	CartService cartService;
	@Autowired
	CartItemService cartItemService;
	@Autowired
	StoreService storeService;

	@RequestMapping(path = "/put", method = RequestMethod.POST)
	public String put(HttpServletRequest request, @RequestParam("goodsId") String goodsId,
			@RequestParam("count") Integer count, @RequestParam("goodsPrice") BigDecimal goodsPrice) {
		DataResult dataResult = new DataResult();
		String userAuthingId = (String) SessionUtil.getAttr(request, SessionAttr.USERAUTHINGID);
		Cart cart = cartService.getUserCart(userAuthingId);
		if (cart == null) {
			cart = new Cart();
			cart.setId(UidUtil.createUUID());
			cart.setUser(userAuthingId);
			cart.setCreated_at(TimeUtil.getNowTimestamp());
			cartService.createCart(cart);
			dataResult.setCode(Code.SERVER_ERROR);
			dataResult.setMessage("用户购物车未成功初始化");
			logger.warn("用户:" + userAuthingId + "的购物车未成功初始化");
			return JsonUtil.toJsonString(dataResult);
		}
		if (!goodsService.isAlive(goodsId)) {
			dataResult.setCode(Code.SERVER_ERROR);
			dataResult.setMessage("商品不存在或商品已被下架,请重新选择");
			return JsonUtil.toJsonString(dataResult);
		}
		Goods goods = goodsService.getGoodsById(goodsId);
		if (!goodsPrice.equals(goods.getPrice())) {
			dataResult.setCode(Code.SERVER_ERROR);
			dataResult.setMessage("商品信息发生变化,请刷新");
			return JsonUtil.toJsonString(dataResult);
		}
		// 如果商品存在购物车则合并数量
		CartItem cartItem = cartItemService.getCartItemByGoodsId(cart.getId(), goodsId);
		if (cartItem != null) {
			cartItem.setCount(cartItem.getCount() + count);
			cartItemService.updateCartItem(cartItem);
			dataResult.setData(cartItem);
			dataResult.setCode(Code.SUCCESS);
			dataResult.setMessage("添加成功");
			return JsonUtil.toJsonString(dataResult);
		}
		cartItem = new CartItem();
		cartItem.setId(UidUtil.createUUID());
		cartItem.setCart(cart.getId());
		cartItem.setGoods(goodsId);
		cartItem.setCount(count);
		cartItem.setStore(goods.getStore());
		cartItem.setCreated_at(TimeUtil.getNowTimestamp());
		cartItem.setUpdated_at(TimeUtil.getNowTimestamp());
		cartService.putItem(cartItem);
		dataResult.setData(cartItem);
		dataResult.setCode(Code.SUCCESS);
		dataResult.setMessage("操作成功");
		return JsonUtil.toJsonString(dataResult);
	}

	@RequestMapping(path = "/update", method = RequestMethod.POST)
	public String updateCart(HttpServletRequest request, @RequestParam("itemId") String itemId,
			@RequestParam("count") Integer count) {
		DataResult dataResult = new DataResult();
		String userAuthingId = (String) SessionUtil.getAttr(request, SessionAttr.USERAUTHINGID);
		CartItem item = cartItemService.getCartItemById(itemId);
		if (item == null) {
			dataResult.setCode(Code.NOT_FOUND);
			dataResult.setMessage("编辑的购物车条目不存在");
			logger.warn("用户:" + userAuthingId + "请求编辑了不存在的购物车条目(" + itemId + ")");
			return JsonUtil.toJsonString(dataResult);
		}
		Cart cart = cartService.getCartById(item.getCart());
		if (cart == null || !cart.getUser().equals(userAuthingId)) {
			dataResult.setCode(Code.FORBIDDEN);
			dataResult.setMessage("所编辑条目不属于当前用户,编辑失败");
			logger.warn("用户:" + userAuthingId + "请求编辑了不属于自己的购物车条目(" + itemId + ")");
			return JsonUtil.toJsonString(dataResult);
		}
		if (count == 0) {
			cartItemService.deleteCartItem(itemId);
		} else {
			item.setCount(count);
			cartItemService.updateCartItem(item);
		}
		dataResult.setCode(Code.SUCCESS);
		dataResult.setMessage("请求成功");
		return JsonUtil.toJsonString(dataResult);
	}

	@RequestMapping(method = RequestMethod.GET)
	public String viewCart(HttpServletRequest request) {
		DataResult dataResult = new DataResult();
		String userAuthingId = (String) SessionUtil.getAttr(request, SessionAttr.USERAUTHINGID);
		Cart viewCart = cartService.viewCart(userAuthingId);
		if(viewCart==null){
			dataResult.setCode(Code.NOT_FOUND);
			dataResult.setMessage("购物车未能初始化!");
			return JsonUtil.toJsonString(dataResult);
		}
		List<CartItemDto> items = viewCart.getItems();
		for (CartItemDto cartItemDto : items) {
			String storeId = cartItemDto.getStore();
			Store store = storeService.getStoreById(storeId);
			storeService.modifyEchoTime(store);
			String storeJson = JSONObject.toJSON(store).toString();
			cartItemDto.setStore(storeJson);
		}
		dataResult.setTotal(items.size());
		dataResult.setData(viewCart);
		dataResult.setCode(Code.SUCCESS);
		dataResult.setMessage("返回成功");
		return JsonUtil.toJsonString(dataResult);
	}

	@RequestMapping(value = "/countPrice", method = RequestMethod.POST)
	public String countPrice(HttpServletRequest request, @RequestParam("itemIds") String itemIds) {
		DataResult dataResult = new DataResult();
		String userAuthingId = (String) SessionUtil.getAttr(request, SessionAttr.USERAUTHINGID);
		List<String> list = UidUtil.splitStringByComma(itemIds);
		if (list == null || list.size() == 0) {
			dataResult.setCode(Code.SERVER_ERROR);
			dataResult.setMessage("参数解析错误");
			return JsonUtil.toJsonString(dataResult);
		}
		List<CartItem> cartItems = cartItemService.getCartItemByItemIdList(list);
		dataResult.setData(cartService.countPrice(cartItems));
		dataResult.setCode(Code.SUCCESS);
		dataResult.setMessage("返回成功");
		return JsonUtil.toJsonString(dataResult);
	}

	@RequestMapping(value = "/countFreight", method = RequestMethod.POST)
	public String countFreight(@RequestParam("itemIds") String itemIds) {
		DataResult dataResult = new DataResult();
		List<String> list = UidUtil.splitStringByComma(itemIds);
		if (list == null || list.size() == 0) {
			dataResult.setCode(Code.SERVER_ERROR);
			dataResult.setMessage("参数解析错误");
			return JsonUtil.toJsonString(dataResult);
		}
		dataResult.setCode(Code.SUCCESS);
		dataResult.setMessage("返回成功");
		dataResult.setData(cartService.countFreight(list));
		return JsonUtil.toJsonString(dataResult);
	}

}
